import { NavBar, Toast, Tabs } from 'antd-mobile'
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import './order.css';
import { order } from '../../api/order';

let url = 'http://jingxun.kuxia.top';

export default function Order() {
  const [activeTab, setActiveTab] = useState('all');
  const [orderData, setOrderData] = useState([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    fetchOrderData();
  }, []);

  const fetchOrderData = async () => {
    try {
      setLoading(true);
      // 从本地存储获取用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      const userId = userInfo.id;
      
      if (!userId) {
        Toast.show({
          content: '未找到用户信息，请重新登录',
          position: 'top'
        });
        setOrderData([]);
        return;
      }
      
      // 调用订单接口
      const response = await order({ id: userId });
      console.log('订单数据', response);
      
      // 处理接口返回的数据
      if (response && response.data) {
        setOrderData(response.data);
      } else {
        setOrderData([]);
      }
    } catch (error) {
      Toast.show({
        content: '获取订单数据失败',
        position: 'top'
      });
      console.error('获取订单数据失败:', error);
      setOrderData([]);
    } finally {
      setLoading(false);
    }
  };

  const back = () => {
    // 返回上一页
    navigate(-1);
  }

  const handleTabChange = (key) => {
    setActiveTab(key);
  }

  // 根据订单状态获取状态文本和样式
  const getOrderStatusText = (state) => {
    switch (state) {
      case 1: return '未付款';
      case 2: return '已付款';
      case 3: return '已发货';
      case 4: return '已收货';
      default: return '未知状态';
    }
  };

  // 根据订单状态过滤订单数据
  const filterOrdersByState = (state) => {
    if (state === 'all') return orderData;
    const stateNum = parseInt(state);
    return orderData.filter(item => item.state === stateNum);
  };

  // 渲染订单列表
  const renderOrderList = (orders) => {
    if (loading) {
      return <div style={{ padding: '16px', textAlign: 'center' }}>加载中...</div>;
    }

    if (orders.length === 0) {
      return (
        <div className="order-content">
          <div className="order-placeholder">
            <img src="https://cdn.jsdelivr.net/npm/sheep-ui@latest/dist/assets/empty-order.png" alt="暂无订单" />
            <p>暂无订单</p>
          </div>
        </div>
      );
    }

    return (
      <div className="order-list">
        {orders.map((item) => (
          <div className="order-item" key={item.order}>
            <div className="order-id-text">订单编号：{item.order}</div>
            {item.commodity && item.commodity.map((commodity, index) => (
              <div className="order-info" key={index}>
                <img src={url + commodity.image} alt={commodity.title} />
                <div className="order-title">{commodity.title}</div>
                <div className="order-status">{getOrderStatusText(item.state)}</div>
              
              </div>
            ))}
            <div className="order-priceBtn">
              <div className="order-price">应付：¥{item.commodity?.reduce((total, commodity) => total + parseFloat(commodity.price || 0), 0).toFixed(2)}</div>
              <div className="order-btn">
                {item.state === 1 && (
                  <>
                    <div className="order-operate" style={{ color: '#000', border: '1px solid #999' }}>取消订单</div>
                    <div className="order-operate" style={{ color: '#E0AF75', border: '1px solid #E0AF75' }}>付款</div>
                  </>
                )}
                {item.state === 2 && (
                  <div className="order-operate" style={{ color: '#000', border: '1px solid #999' }}>提醒发货</div>
                )}
                {item.state === 3 && (
                  <div className="order-operate" style={{ color: '#E0AF75', border: '1px solid #E0AF75' }}>确认收货</div>
                )}
                {item.state === 4 && (
                  <div className="order-operate" style={{ color: '#000', border: '1px solid #999' }}>删除订单</div>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>
    );
  };

  const allOrders = filterOrdersByState('all');
  const pendingOrders = filterOrdersByState(1);
  const shippingOrders = filterOrdersByState(3);
  const completedOrders = filterOrdersByState(4);
  const cancelledOrders = [];

  return (
    <div className="order-page">
      <NavBar onBack={back}>我的订单</NavBar>
      <Tabs 
        activeKey={activeTab} 
        onChange={handleTabChange}
        style={{
          '--active-line-color': '#E0AF75',
          '--active-title-color': '#E0AF75'
        }}
      >
        <Tabs.Tab title='全部' key='all'>
          {renderOrderList(allOrders)}
        </Tabs.Tab>
        <Tabs.Tab title='待付款' key='pending'>
          {renderOrderList(pendingOrders)}
        </Tabs.Tab>
        <Tabs.Tab title='待收货' key='shipping'>
          {renderOrderList(shippingOrders)}
        </Tabs.Tab>
        <Tabs.Tab title='已完成' key='completed'>
          {renderOrderList(completedOrders)}
        </Tabs.Tab>
        <Tabs.Tab title='已取消' key='cancelled'>
          {renderOrderList(cancelledOrders)}
        </Tabs.Tab>
      </Tabs>
    </div>
  )
}